package com.lkd.controller;

import cn.hutool.core.bean.BeanUtil;
import com.lkd.dto.SkuDto;
import com.lkd.entity.Sku;
import com.lkd.result.PageBean;
import com.lkd.result.Result;
import com.lkd.service.SkuService;
import com.lkd.utils.OssTemplate;
import com.lkd.vo.SkuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/vm-service/sku")
public class SkuController {
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private SkuService service;

    /**
     * 上传文件
     * @param fileName
     * @return
     * @throws IOException
     */
    @PostMapping("/fileUpload")
    public Result uploadFile(MultipartFile fileName) throws IOException {
        String filePath = ossTemplate.upload(fileName.getOriginalFilename(), fileName.getInputStream());
        log.info("文件上传成功,访问地址是：{}", filePath);
        return Result.success(filePath);
    }

    /**
     * 新增商品
     * @param skuDto
     * @return
     */
    @PostMapping
    public Result saveSku(@RequestBody SkuDto skuDto) {
        Sku sku = BeanUtil.toBean(skuDto, Sku.class);
        service.saveSku(sku);
        return Result.success(true);
    }

    /**
     * 分页查询商品
     * @param pageIndex
     * @param pageSize
     * @param skuName
     * @return
     */
    @GetMapping("/search")
    public Result getSku(
            @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "skuName", required = false) String skuName
    ) {
        PageBean<SkuVo> pageBean = service.pageConditonQuerySku(pageIndex, pageSize, skuName);
        return Result.success(pageBean);
    }

    /**
     * 修改商品
     * @param skuDto
     * @return
     */
    @PutMapping
    public Result updateSku(@RequestBody SkuDto skuDto) {
        service.updateSku(skuDto);
        return Result.success(true);
    }
}